package cn._2dland.uploader.sixrooms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import cn._2dland.uploader.utils.IniFile;
import cn._2dland.uploader.utils.Logger;

public class CUIUploader {
	private IniFile ini = null;

	public CUIUploader() {
		String home = System.getProperty("user.dir");
		String fileSep = System.getProperty("file.separator");
		if(!home.endsWith(fileSep))
			home += fileSep;
		ini = new IniFile(home + "6cn.ini");
	}

	public void start(String taskFile){
		// 解析任务
		List<SixRoomsTask> tasks = parseTasks(taskFile);
		if(tasks == null || tasks.size() <= 0) {
			Logger.writec("没有需要执行的任务，程序退出...");
			return;
		}
		else {
			Logger.writec("任务文件解析完毕!");
			Logger.writec("待执行的任务: " + tasks.size() + " 项");
		}

		// 读取账户配置
		String user = ini.getConfigValue("account", "username");
		String pass = ini.getConfigValue("account", "password");
		SixRoomsClient client = new SixRoomsClient(user, pass);
		// 尝试登录
		while(!client.isLogin()){
			client.login();
		}
		// 获取延时时间
		int delay = 10;
		try{
			String delayStr = ini.getConfigValue("upload", "delay", "10");
			delay = Integer.parseInt(delayStr);
			delay = (delay < 0) ? 10 : delay; 
		}
		catch (Exception e) { delay = 10; }
		delay *= 1000;
		// 执行上传任务
		for(int i=0; i<tasks.size(); i++){
			SixRoomsTask task = tasks.get(i);
			client.upload(task);
			// 自动删除文件
			if("yes".equals(ini.getConfigValue("upload", "autoDELETE")))
				task.deleteFile();
			// 延迟
			try{ Thread.sleep(delay); }
			catch (Exception e) {}
		}
		Logger.writec("全部任务上传完成!");
	}

	/**
	 * 解析任务定义文件
	 * @param taskFile
	 * @return
	 */
	private List<SixRoomsTask> parseTasks(String taskFile) {
		List<SixRoomsTask> tasks = null;
		try {
			tasks = new ArrayList<SixRoomsTask>();
			
			FileInputStream fis = new FileInputStream(taskFile);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
			for(String line; (line=br.readLine())!=null; ){
				// 注释行，跳过
				if(line.matches("^//.*$")) {
					continue;
				}
				// 长度不够，跳过
				if(line.length() <= 11) {
					continue;
				}
				// 按|分割行
				String[] tmp = line.split("\\|");
				// 分割后不足6项，跳过
				if(tmp.length < 6) {
					continue;
				}
				// 构造任务
				SixRoomsTask task = new SixRoomsTask();
				task.title = tmp[0];
				task.descript = tmp[1];
				task.tags = tmp[2];
				task.cid = Integer.parseInt(tmp[3]);
				task.status = Integer.parseInt(tmp[4]);
				task.file = new File(tmp[5]);
				// 是否强制使用flvx扩展名
				task.forceFLVX = "yes".equals(ini.getConfigValue("upload", "forceFLVX"));
				// 添加到任务列表
				tasks.add(task);
			}
			br.close();
			fis.close();
		}
		catch (Exception e) {
			tasks = null;
			e.printStackTrace(System.err);
		}
		return tasks;
	}
}